#include "udpserverthread.h"

UdpServerThread::UdpServerThread(QObject *parent, quint16 port) : QThread(parent)
{
        socket = new QUdpSocket(this);
        if (socket->bind(QHostAddress::Any, port)) {
            qDebug() << QString("Server started on port %1").arg(port);
            connect(socket, &QUdpSocket::readyRead,
                    this, &UdpServerThread::readPendingDatagrams);
        } else {
            qDebug() << QString("Server could not bind to port %1").arg(port);
        }
}

void UdpServerThread::readPendingDatagrams()
{
    while (socket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        emit datagramReceived(datagram, sender, senderPort);
    }
}

/*
void UdpServerThread::run()
{
    exec();
}
*/
